<?php

namespace Frieza\Modules\Create\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Doraemon\model\Create\Official as mOfficial;
use Doraemon\service\Create\Official as sOfficial;

class OfficialController extends Controller
{

    public function index(Request $request, Content $content)
    {
        $params = $request->all();
        $page = $request->input('page', 1);
        $pageSize = $request->input('pageSize', 20);
        $limit = [($page - 1) * $pageSize, $pageSize];
        $order = ['sort' => 'ASC', 'start_time' => 'DESC'];
        $where['status'] = mOfficial::STATUS_NORMAL;
        $data = sOfficial::getList($where, $page, $pageSize, $order);

        $gridModel = new pGridDataModel($data['list'], $data['total'], ['perPage' => $pageSize]);
        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableFilter();
            $grid->column('id', 'ID')->sort('sort');
            $grid->column('pic_id', '图片')->display(function () {
                return "<img src='" . ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $this->pic_id, ImgUrl::IMAGE_SIZE_OP_ORI) . "' width='200' />";
            });
            $grid->column('start_time', '开始时间');
            $grid->column('end_time', '结束时间');
            $grid->column('link', '链接地址')->linkSelect(false, null, false);
            $grid->column('status', '状态');
        });
        return $content
            ->header('官方活动列表')
            ->breadcrumb(['text' => '官方活动列表', 'url' => '/admin/topic/hot/index'])
            ->body($listGrid);
    }


    public function create(Content $content, $id = 0)
    {
        $info = [];
        if ($id) {
            $info = sOfficial::getDetial($id);
            $info = self::formatInfo($info);
        }
        $form = new Form($info);
        $form->hidden('id', 'id');
        $form->imgUpload('pic_id', '上传图片', false, ['imgType' => ImgUrl::APPTYPE_OP, 'imgSize' => ImgUrl::IMAGE_SIZE_OP_ORI]);
        $form->dateRange('start_time', 'end_time', '上线-下线时间')->required();
        $form->linkSelect('link', '活动链接');
        $form->action('/admin/create/official/save');
        return $content
            ->header('创建订单')
            ->breadcrumb(['text' => '官方活动', 'url' => ''], ['text' => '创建官方活动'])
            ->row($form->render());
    }

    public static function save(Request $request)
    {
        $param = $request->all();
        $data['pic_id'] = $param['pic_id'];
        $data['link_type'] = $param['link_type'];
        $data['start_time'] = strtotime($param['start_time']);
        $data['end_time'] = strtotime($param['end_time']) + 24 * 60 * 60 - 1;
        $data['link_params'] = json_encode($param['link_params'], JSON_UNESCAPED_UNICODE);
        if ($param['id']) {
            $result = mOfficial::edit($param['id'], $data);
        } else {
            $result = mOfficial::addData($data);
        }
        if ($result) {
            $success = new MessageBag([
                'title' => '保存成功'
            ]);
            return redirect('/admin/create/official/index')->with(compact('success'));
        }
    }

    /**
     * 拖动排序
     *
     * @param Request $request
     */
    public function sort(Request $request)
    {
        $params = $request->all();
        $list = $params['sort'];
        foreach ($list as $id => $sort) {
            sOfficial::edit($id, ['sort' => $sort]);
        }
    }

    public function del($id)
    {
        $return = sOfficial::edit($id, ['status' => mOfficial::STATUS_DELETE]);
        if ($return) {
            return response()->json([
                'status' => true,
                'message' => "操作成功",
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
    }

    private static function formatInfo($info)
    {
        $info['start_time'] = date('Y-m-d', $info['start_time']);
        $info['end_time'] = date('Y-m-d', $info['end_time']);
        if ($info['link_type']) {
            $info['link'] = [
                "link_type" => $info['link_type'],
                "link_params" => json_decode($info['link_params'], 1)
            ];
        }
        return $info;
    }
}